package org.peoples.rooms {
	
	import com.qualityattributes.collections.ICollection;
	import com.qualityattributes.collections.maps.HashMap;
	import com.qualityattributes.errors.UnsupportedOperationError;
	import com.qualityattributes.lang.QInteger;
	
	import flash.events.EventDispatcher;
	
	public class RoomPool extends EventDispatcher {
		
		private var rooms:HashMap;
		private static var instance:RoomPool;
		private static var _instanceCheck:int = 0;
		
		public function RoomPool():void {
			if (_instanceCheck == 0)
				throw new UnsupportedOperationError("RoomPool must be instantiated by using RoomPool.getInstance()");
				
			this.rooms = new HashMap();
		}
		
		public function addRoom(room:RoomProperties):Boolean {
			if (!rooms.containsValue(room)) {
				rooms.putItem(new QInteger(room.ID), room);
				
				var evt:RoomPoolEvent = new RoomPoolEvent(RoomPoolEvent.ROOM_ADDED, room);
				dispatchEvent(evt);
				
				return true;
			}
			
			return false;
		}
		
		public function getAllRooms():ICollection {
			return rooms.values();
		}
		
		public static function getInstance():RoomPool {
			_instanceCheck = 1;
			
			if (instance == null)
				instance = new RoomPool();
				
			return instance;
		}
		
		public function getRoom(id:int):RoomProperties {
			return rooms.getItem(new QInteger(id)) as RoomProperties;
		}
		
		public function removeRoom(id:int):RoomProperties {
			var room:RoomProperties = rooms.remove(new QInteger(id)) as RoomProperties;
			
			if (room != null) {
				var evt:RoomPoolEvent = new RoomPoolEvent(RoomPoolEvent.ROOM_REMOVED, room);
				dispatchEvent(evt);
			}
			
			return room;
		}
		
	}
	
}